package org.springblade.modules.repair.controller;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

/**
 * 物业端中转 控制器
 *
 * @author BladeX
 * @since 2021-05-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("repair/to/estate")
@Api(value = "物业端中转", tags = "物业端中转管理")
public class EstateController extends BladeController {

	private final ProjectApiConfiguration projectApiConfiguration;

	@PostMapping("/invoke")
	public JSONObject invoke(@RequestBody Map<String, Object> params) {
		if (!params.containsKey("url")) {
			throw new ServiceException("请求路径不能为空！");
		}
		if (!params.containsKey("method")) {
			throw new ServiceException("http请求方式不能为空！");
		}

		HttpResponse res = null;
		String url =  projectApiConfiguration.getEstate() + params.get("url");
		String method = String.valueOf(params.get("method"));
		if (method.equals("get") || method.equals("GET")) {
			res = createGet(url, null);
		} else if (method.equals("post") || method.equals("POST")) {
			String body = params.containsKey("body") ? JSONUtil.toJsonStr(params.get("body")) : null;
			res = createPost(url, body);
		} else {
			throw new ServiceException("http请求方式非法！");
		}

		JSONObject resObj = JSONUtil.parseObj(res.body(), true);
		if (Integer.valueOf(resObj.get("code").toString()) != 200) {
			throw new ServiceException(resObj.get("msg").toString());
		}
		return resObj;
	}

	/**
	 *  POST请求 (携带token)
	 * @param url
	 * @param body
	 */
	public HttpResponse createPost(String url, String body){
		return HttpUtil.createPost(url).header(TokenConstant.HEADER, AuthUtil.getHeader(this.getRequest())).body(body).execute();
	}

	/**
	 *  GET请求 (携带token)
	 * @param url
	 * @param body
	 */
	public HttpResponse createGet(String url, String body){
		return HttpUtil.createGet(url).header(TokenConstant.HEADER, AuthUtil.getHeader(this.getRequest())).body(body).execute();
	}
}
